<template>
  <div 
    class="bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow cursor-pointer border border-gray-200 overflow-hidden"
    @click="handleClick"
  >
    <!-- 顶部状态栏 -->
    <div class="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <!-- 状态标识 -->
        <component 
          :is="getStatusIcon()" 
          class="w-4 h-4"
          :class="getStatusColor()"
        />
        <span class="text-sm font-medium" :class="getStatusColor()">
          {{ getStatusText() }}
        </span>
      </div>
      
      <!-- 学段标签 -->
      <span class="px-2 py-1 text-xs font-medium rounded" :class="getGradeLevelBadge()">
        {{ getGradeLevelText() }}
      </span>
    </div>
    
    <!-- 主要内容 -->
    <div class="p-6">
      <div class="flex items-start justify-between mb-4">
        <!-- 标题和日期 -->
        <div class="flex-1 min-w-0 mr-4">
          <h3 class="text-lg font-medium text-gray-900 truncate mb-1">
            {{ essay.title || '未命名作文' }}
          </h3>
          <div class="flex items-center space-x-4 text-sm text-gray-500">
            <div class="flex items-center space-x-1">
              <Calendar class="w-4 h-4" />
              <span>{{ formatDate(essay.createdAt) }}</span>
            </div>
            <div class="flex items-center space-x-1" v-if="essay.content">
              <FileText class="w-4 h-4" />
              <span>{{ essay.content.length }} 字</span>
            </div>
          </div>
        </div>
        
        <!-- 分数徽章 -->
        <div v-if="essay.status === 'completed' && essay.score !== undefined" class="flex-shrink-0">
          <div 
            class="w-16 h-16 rounded-full flex items-center justify-center border-4"
            :class="getScoreBorderClass()"
          >
            <div class="text-center">
              <div class="text-2xl font-bold" :class="getScoreColorClass()">
                {{ essay.score }}
              </div>
              <div class="text-xs text-gray-500">分</div>
            </div>
          </div>
        </div>
        
        <!-- 处理中动画 -->
        <div v-else-if="essay.status === 'processing'" class="flex-shrink-0">
          <div class="w-16 h-16 rounded-full flex items-center justify-center bg-blue-50 border-4 border-blue-200">
            <Loader class="w-8 h-8 text-blue-500 animate-spin" />
          </div>
        </div>
        
        <!-- 待提交 -->
        <div v-else class="flex-shrink-0">
          <div class="w-16 h-16 rounded-full flex items-center justify-center bg-gray-100 border-4 border-gray-200">
            <Clock class="w-8 h-8 text-gray-400" />
          </div>
        </div>
      </div>
      
      <!-- 作文预览 -->
      <div class="text-sm text-gray-600 line-clamp-3 leading-relaxed mb-4">
        {{ essay.content?.substring(0, 150) || '暂无内容' }}{{ essay.content?.length > 150 ? '...' : '' }}
      </div>
      
      <!-- 批改信息 -->
      <div v-if="essay.status === 'completed' && essay.correctionResult" class="pt-4 border-t border-gray-100">
        <div class="flex items-center justify-between text-sm">
          <div class="flex items-center space-x-4">
            <!-- 发现问题 -->
            <div class="flex items-center space-x-1">
              <AlertCircle class="w-4 h-4 text-red-500" />
              <span class="text-gray-600">
                {{ essay.correctionResult.error_count || 0 }} 个问题
              </span>
            </div>
            
            <!-- 批改时间 -->
            <div class="flex items-center space-x-1" v-if="essay.correctedAt">
              <Clock class="w-4 h-4 text-gray-400" />
              <span class="text-gray-500">
                {{ formatDate(essay.correctedAt) }}
              </span>
            </div>
          </div>
          
          <!-- 查看按钮 -->
          <button
            @click.stop="viewResult"
            class="inline-flex items-center space-x-1 px-3 py-1 text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-colors"
          >
            <Eye class="w-4 h-4" />
            <span>查看报告</span>
          </button>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div v-else-if="essay.status === 'pending' || essay.status === 'draft'" class="pt-4 border-t border-gray-100">
        <div class="flex items-center justify-end space-x-2">
          <button
            v-if="essay.status === 'draft'"
            @click.stop="editEssay"
            class="inline-flex items-center space-x-1 px-3 py-1 text-gray-600 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <Edit3 class="w-4 h-4" />
            <span>继续编辑</span>
          </button>
          
          <button
            @click.stop="submitForCorrection"
            :disabled="isSubmitting"
            class="inline-flex items-center space-x-1 px-3 py-1 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Send class="w-4 h-4" :class="{ 'animate-pulse': isSubmitting }" />
            <span>{{ isSubmitting ? '提交中...' : '提交批改' }}</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { 
  CheckCircle, 
  Clock, 
  Loader, 
  AlertCircle, 
  Calendar, 
  FileText, 
  Eye,
  Edit3,
  Send,
  FileX
} from 'lucide-vue-next';
import { useCorrectionStore } from '../stores/correction.js';

/**
 * EssayCard 组件
 * 显示单个作文的卡片信息
 */

// ==================== Props ====================
const props = defineProps({
  /**
   * 作文数据
   * @type {{ id: string, title: string, gradeLevel: string, content: string, status: string, score: number, createdAt: string, correctedAt: string, correctionResult: object }}
   */
  essay: {
    type: Object,
    required: true,
  },
});

// ==================== Emits ====================
const emit = defineEmits(['edit', 'submit', 'view']);

// ==================== Composition API ====================
const router = useRouter();
const correctionStore = useCorrectionStore();

// ==================== Refs ====================
const isSubmitting = ref(false);

// ==================== Methods ====================

/**
 * 格式化日期
 */
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;
  const dayDiff = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (dayDiff === 0) {
    const hourDiff = Math.floor(diff / (1000 * 60 * 60));
    if (hourDiff === 0) {
      const minuteDiff = Math.floor(diff / (1000 * 60));
      return minuteDiff <= 1 ? '刚刚' : `${minuteDiff}分钟前`;
    }
    return `${hourDiff}小时前`;
  } else if (dayDiff === 1) {
    return '昨天';
  } else if (dayDiff < 7) {
    return `${dayDiff}天前`;
  } else {
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit' 
    });
  }
};

/**
 * 获取状态图标
 */
const getStatusIcon = () => {
  const icons = {
    'completed': CheckCircle,
    'processing': Loader,
    'pending': Clock,
    'draft': FileX,
    'failed': AlertCircle,
  };
  return icons[props.essay.status] || Clock;
};

/**
 * 获取状态颜色
 */
const getStatusColor = () => {
  const colors = {
    'completed': 'text-green-600',
    'processing': 'text-blue-600',
    'pending': 'text-amber-600',
    'draft': 'text-gray-600',
    'failed': 'text-red-600',
  };
  return colors[props.essay.status] || 'text-gray-600';
};

/**
 * 获取状态文本
 */
const getStatusText = () => {
  const texts = {
    'completed': '已批改',
    'processing': '批改中',
    'pending': '待批改',
    'draft': '草稿',
    'failed': '批改失败',
  };
  return texts[props.essay.status] || '未知状态';
};

/**
 * 获取学段徽章样式
 */
const getGradeLevelBadge = () => {
  const badges = {
    'primary': 'bg-purple-100 text-purple-800',
    'middle': 'bg-blue-100 text-blue-800',
    'high': 'bg-red-100 text-red-800',
  };
  return badges[props.essay.gradeLevel] || 'bg-gray-100 text-gray-800';
};

/**
 * 获取学段文本
 */
const getGradeLevelText = () => {
  const texts = {
    'primary': '小学',
    'middle': '初中',
    'high': '高中',
  };
  return texts[props.essay.gradeLevel] || '未知';
};

/**
 * 获取分数颜色类名
 */
const getScoreColorClass = () => {
  const score = props.essay.score;
  if (score < 60) return 'text-red-600';
  if (score < 80) return 'text-yellow-600';
  if (score < 90) return 'text-blue-600';
  return 'text-green-600';
};

/**
 * 获取分数边框样式
 */
const getScoreBorderClass = () => {
  const score = props.essay.score;
  if (score < 60) return 'border-red-200 bg-red-50';
  if (score < 80) return 'border-yellow-200 bg-yellow-50';
  if (score < 90) return 'border-blue-200 bg-blue-50';
  return 'border-green-200 bg-green-50';
};

/**
 * 点击卡片
 */
const handleClick = () => {
  if (props.essay.status === 'completed') {
    viewResult();
  } else if (props.essay.status === 'draft') {
    editEssay();
  }
};

/**
 * 查看批改结果
 */
const viewResult = () => {
  emit('view', props.essay);
  router.push(`/correction/${props.essay.id}`);
};

/**
 * 编辑作文
 */
const editEssay = () => {
  emit('edit', props.essay);
  router.push(`/submit?essayId=${props.essay.id}`);
};

/**
 * 提交批改
 */
const submitForCorrection = async () => {
  if (isSubmitting.value) return;
  
  isSubmitting.value = true;
  
  try {
    console.log('[EssayCard] Submitting correction for essay:', props.essay.id);
    await correctionStore.submitForCorrection(props.essay.id);
    emit('submit', props.essay);
    
    console.log('[EssayCard] Correction submitted, navigating to result page...');
    
    // 跳转到批改结果页（添加fresh参数标记为新提交）
    router.push({
      path: `/correction/${props.essay.id}`,
      query: { fresh: 'true' }  // 标记为新提交的批改
    });
  } catch (error) {
    console.error('[EssayCard] Submit failed:', error);
    alert('提交失败：' + (error.message || '未知错误'));
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
/* 限制文本显示行数 */
.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>

